/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package diepafi;

import java.awt.HeadlessException;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import model.Playlist;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import model.Song;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import programm.DBmanager;

/**
 *
 * @author leo
 */
public class PlaylistSongGUI extends javax.swing.JFrame {
    private static EntityManager em;
    private Playlist editPlaylist; 
    private MainMenuGUI mmg;
    
    Calendar calendar = Calendar.getInstance();    
    Date now = calendar.getTime();
    //περνάμε την τρέχουσα ημερομηνία και ώρα σε μια Timestamp για να ενημερώσουμε
    //το αντίστοιχο πεδίο της playlist (ημερομηνία δημιουργίας/τροποποίησης
    Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
   
    /**
     * Creates new form PlaylistSongGUI   (R17)
     */
    public PlaylistSongGUI() {
        DBmanager dbm = new DBmanager(); 
        PlaylistSongGUI.em=dbm.getEm();
        
        initComponents();
    }
    
    //κατασκευαστής με παράμετρο για να θυμάται το γονικό παράθυρο
    public PlaylistSongGUI(MainMenuGUI mmg) {
        DBmanager dbm = new DBmanager(); 
        PlaylistSongGUI.em=dbm.getEm();
         
        this.mmg=mmg;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        RadioStation_appPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("RadioStation_appPU").createEntityManager();
        playlistQuery = java.beans.Beans.isDesignTime() ? null : RadioStation_appPUEntityManager.createQuery("SELECT p FROM Playlist p WHERE p.listId IS NOT NULL");
        playlistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(playlistQuery.getResultList());
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButtonAdd = new javax.swing.JButton();
        jButtonEdit = new javax.swing.JButton();
        jButtonDelete = new javax.swing.JButton();
        jButtonExit = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTablePlaylist = new javax.swing.JTable();
        jButtonExportXml = new javax.swing.JButton();
        jButtonImportXml = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Λίστες τραγουδιών");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));
        jPanel1.setForeground(new java.awt.Color(255, 255, 255));

        jLabel1.setBackground(new java.awt.Color(0, 0, 0));
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Λίστες τραγουδιών");

        jButtonAdd.setBackground(new java.awt.Color(0, 0, 0));
        jButtonAdd.setForeground(new java.awt.Color(255, 255, 255));
        jButtonAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/treble4.png"))); // NOI18N
        jButtonAdd.setText("Δημιουργία");
        jButtonAdd.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButtonAdd.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButtonAdd.setNextFocusableComponent(jButtonEdit);
        jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddActionPerformed(evt);
            }
        });

        jButtonEdit.setBackground(new java.awt.Color(0, 0, 0));
        jButtonEdit.setForeground(new java.awt.Color(255, 255, 255));
        jButtonEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/gtk-edit.png"))); // NOI18N
        jButtonEdit.setText("Ενημέρωση");
        jButtonEdit.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButtonEdit.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButtonEdit.setNextFocusableComponent(jButtonDelete);
        jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEditActionPerformed(evt);
            }
        });

        jButtonDelete.setBackground(new java.awt.Color(0, 0, 0));
        jButtonDelete.setForeground(new java.awt.Color(255, 255, 255));
        jButtonDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/delete.png"))); // NOI18N
        jButtonDelete.setText("Διαγραφή");
        jButtonDelete.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButtonDelete.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButtonDelete.setNextFocusableComponent(jButtonExit);
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteActionPerformed(evt);
            }
        });

        jButtonExit.setBackground(new java.awt.Color(0, 0, 0));
        jButtonExit.setForeground(new java.awt.Color(255, 255, 255));
        jButtonExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/stock_exit.png"))); // NOI18N
        jButtonExit.setText("Έξοδος");
        jButtonExit.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jButtonExit.setNextFocusableComponent(jButtonAdd);
        jButtonExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExitActionPerformed(evt);
            }
        });

        jTablePlaylist.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTablePlaylist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playlistList, jTablePlaylist);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${listTitle}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Περιγραφή");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${creation}"));
        columnBinding.setColumnName("Δημιουργία");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTablePlaylist);

        jButtonExportXml.setBackground(new java.awt.Color(0, 0, 0));
        jButtonExportXml.setForeground(new java.awt.Color(255, 255, 255));
        jButtonExportXml.setText("Εξαγωγή XML");
        jButtonExportXml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExportXmlActionPerformed(evt);
            }
        });

        jButtonImportXml.setBackground(new java.awt.Color(0, 0, 0));
        jButtonImportXml.setForeground(new java.awt.Color(255, 255, 255));
        jButtonImportXml.setText("Εισαγωγή XML");
        jButtonImportXml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImportXmlActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonImportXml, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonExportXml, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonEdit, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
                    .addComponent(jButtonAdd, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonExit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButtonAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonEdit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonDelete)
                        .addGap(161, 161, 161)
                        .addComponent(jButtonExportXml)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonImportXml)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonExit))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExitActionPerformed
        mmg.setEnabled(true);
        this.dispose(); //κλείσιμο παραθύρου
    }//GEN-LAST:event_jButtonExitActionPerformed

    private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddActionPerformed
        PlaylistSongEditGUI frame = new PlaylistSongEditGUI(this, true);
        frame.setTitle("Δημιουργία");
        frame.setLocation((int) this.getLocation().getX(),(int) this.getLocation().getY());
        frame.setVisible(true);
        if(frame.getReturnStatus()==1) {
            playlistList.add(frame.getAddPlaylist()); //"εισάγει" τη νέα playlist στον πίνακα
            jTablePlaylist.repaint();
        }       
    }//GEN-LAST:event_jButtonAddActionPerformed

    private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
        int s = jTablePlaylist.getSelectedRow();
        int dialogButton = JOptionPane.YES_NO_OPTION;
        
        if (s>-1) {
              if(em == null){
                  //μήνυμα σε περίπτωση που δεν έχει επιλεχθεί Playlist
                JOptionPane.showMessageDialog(this, "Παρακαλώ επιλέξτε Λίστα Τραγουδιών για διαγραφή"); 
            }else {
                int deleteId=playlistList.get(s).getListId(); //ανάκτηση του id της προς διαγραφή λίστας - βρίσκεται στην ίδια θέση με την γραμμή του πίνακα
                //ζητά επιβεβαίωση από τον χρήστη
                if (JOptionPane.showConfirmDialog(this, "Είστε σίγουροι ότι θέλετε διαγράψατε τη Λίστα "+ jTablePlaylist.getValueAt(s, 0),"Προειδοποίηση…",dialogButton)==0) {
                    try {
                       //Query για διαγραφή Λίστας.
                       em.getTransaction().begin();
                       Query q=em.createQuery("DELETE FROM Playlist p WHERE p.listId="+deleteId, Playlist.class);
                       q.executeUpdate(); 
                       em.getTransaction().commit();                      
                       playlistList.remove(s);  //διαγράφει την playlist από την λίστα για να εμφανιστούν οι αλλαγές στον πίνακα
                       jTablePlaylist.repaint();
                       //Αφού γίνει διαγραφή εμφανίζει μήνυμα
                       JOptionPane.showMessageDialog(this, "Η διαγραφή ολοκληρώθηκε με επιτυχία!");
                     } catch (Exception e) {
                          em.getTransaction().rollback();
                      }                  

                }
            }
        }else{
            JOptionPane.showMessageDialog(this, "Παρακαλώ επιλέξτε μια Λίστα Τραγουδιών για διαγραφή"); 
        
    }//GEN-LAST:event_jButtonDeleteActionPerformed
    }
    private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditActionPerformed
        //δημιουργεί ένα νέο παράθυρο διαχείρισης Λίστας
        //κρατώντας τα στοιχεία της επιλεγμένης γραμμής του πίνακα άλμπουμ
        int s=jTablePlaylist.getSelectedRow(); //η επιλεγμένη γραμμή του πίνακα
        if (s>-1) {  //πρόβλεψη για την περίπτωση που δεν έχει γίνει κάποια επιλογή
            if(em==null) {JOptionPane.showMessageDialog(this, "Παρακαλώ επιλέξτε μια Λίστα για επεξεργασία"); //Μήνυμα
            } else {
                int editId=playlistList.get(s).getListId();
                //αντλεί μια λίστα από την βάση
                em.clear();
                Query q1=em.createQuery("SELECT p FROM Playlist p WHERE p.listId="+editId, Playlist.class);
                editPlaylist=(Playlist) q1.getResultList().get(0); 
                PlaylistSongEditGUI frame = new PlaylistSongEditGUI(this, true);
                frame.setTitle("Επεξεργασία");
                frame.setPlaylist(editPlaylist); //περνά την προς επεξεργασία λίστα
                frame.setFields(); //περνά τα στοιχεία της επιλεγμένης Λίστας στα πεδία της φόρμας
                frame.setLocation((int) this.getLocation().getX(),(int) this.getLocation().getY());
                frame.setVisible(true); //"ενεργοποιεί" το νέο παράθυρο
                if(frame.getReturnStatus()==1) {
                    //εμφανίζει τα νέα στοιχεία της επεξεργασμένης λίστας στον πίνακα
                    Playlist editedPlaylist=frame.getAddPlaylist();
                    int index=0;
                    for(Playlist p: playlistList) {
                        if(Objects.equals(p.getListId(), editedPlaylist.getListId())) {
                            break;
                        }
                        index++;
                    }
                    playlistList.set(index, editedPlaylist);
                    jTablePlaylist.repaint();
                } 
            }                                           
        } else{
            JOptionPane.showMessageDialog(this, "Παρακαλώ επιλέξτε μια Λίστα για επεξεργασία"); //Μήνυμα
        }                                                
                       
    }//GEN-LAST:event_jButtonEditActionPerformed

    private void jButtonExportXmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExportXmlActionPerformed
        
        Playlist exportPlaylist = new Playlist(); //αποθηκεύει την επιλεγμένη playlist

        int s=jTablePlaylist.getSelectedRow(); //η επιλεγμένη γραμμή του πίνακα
        if (s>-1) {  //πρόβλεψη για την περίπτωση που δεν έχει γίνει κάποια επιλογή
            if(RadioStation_appPUEntityManager==null) {JOptionPane.showMessageDialog(this, "Παρακαλώ επιλέξτε μια Λίστα για εξαγωγή"); //Μήνυμα
            } else {
                int exportId=playlistList.get(s).getListId();
                //αντλεί τη λίστα από την βάση
                RadioStation_appPUEntityManager.clear();
                Query q1 = RadioStation_appPUEntityManager.createQuery("SELECT p FROM Playlist p WHERE p.listId="+exportId, Playlist.class);
                exportPlaylist=(Playlist) q1.getResultList().get(0); 
                
                try{
                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();        
                    Document document = documentBuilder.newDocument();
        
                    Element element =  document.createElement("Playlist");
                    document.appendChild(element);
        
                    Attr attr1 = document.createAttribute("playlist");
                    attr1.setValue(exportPlaylist.getListTitle());
                    element.setAttributeNode(attr1);
            
                    Element name = document.createElement("Τίτλος_Λίστας");
                    name.appendChild(document.createTextNode(exportPlaylist.getListTitle()));
                    element.appendChild(name);
                
                    Element description = document.createElement("Περιγραφή");
                    description.appendChild(document.createTextNode(exportPlaylist.getDescription()));
                    element.appendChild(description);
                
                    Element creation = document.createElement("Δημιουργία");
                    creation.appendChild(document.createTextNode(exportPlaylist.getCreation().toString()));
                    element.appendChild(creation);

                    Element element1 =  document.createElement("Song");
                    element.appendChild(element1);
        
                    Attr attr2 = document.createAttribute("song");
                    attr2.setValue("Τραγούδια");
                    element1.setAttributeNode(attr2);
           
                    for (Song song: exportPlaylist.getSongCollection()){        
                        Element songName = document.createElement("Τίτλος_Τραγουδιού");
                        songName.appendChild(document.createTextNode(song.getSongTitle()));
                        element1.appendChild(songName);
        
                        Element track = document.createElement("Καλλιτέχνης_Συγκρότημα");
                        try {
                            track.appendChild(document.createTextNode(song.getAlbumId().getArtistId().getArtisticName()));
                            element1.appendChild(track);
                        } catch(NullPointerException n) {
                            track.appendChild(document.createTextNode(song.getAlbumId().getGroupId().getGroupName()));
                            element1.appendChild(track);                    
                        }
                        String dur=""+song.getDuration();
                        Element duration = document.createElement("Διάρκεια");
                        duration.appendChild(document.createTextNode(dur.substring(0, 3)));
                        element1.appendChild(duration);
                    }
        
                    TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    Transformer transformer = transformerFactory.newTransformer();
                    DOMSource source = new DOMSource(document);
        
                    JFrame parentFrame = new JFrame();
                    FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("xml files (*.xml)", "xml");
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setFileFilter(xmlfilter);
                    fileChooser.setDialogTitle("Εξαγωγή λίστας σε αρχείο XML");
                    int userSelection = fileChooser.showSaveDialog(parentFrame);
        
                    if (userSelection == JFileChooser.APPROVE_OPTION){            
                        StreamResult streamResult = new StreamResult(fileChooser.getSelectedFile()+".xml");
                        transformer.transform(source, streamResult);
                        File fileToSave = fileChooser.getSelectedFile();
                        JOptionPane.showMessageDialog(this, "Το αρχείο αποθηκεύτηκε στο: " + fileToSave.getAbsolutePath());        
                    }    
                } catch (ParserConfigurationException | DOMException | HeadlessException | TransformerException ex) {
                }
            }                                           
        } else{
            JOptionPane.showMessageDialog(this, "Παρακαλώ επιλέξτε μια Λίστα για εξαγωγή"); //Μήνυμα
        }     
 
    }//GEN-LAST:event_jButtonExportXmlActionPerformed

    private void jButtonImportXmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImportXmlActionPerformed
        Playlist newPlaylist = new Playlist();
        List<Song> songs=new ArrayList();
        Song addSong=new Song();

        try{    
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("xml files (*.xml)", "xml");            
            chooser.setFileFilter(xmlfilter);
            chooser.setDialogTitle("Εισαγωγή λίστας απο αρχείο XML");
            chooser.showOpenDialog(null);
            File xmlFile = chooser.getSelectedFile();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(xmlFile);

            NodeList list = document.getElementsByTagName("Playlist");
            
            Node node = list.item(0);
            Element element = (Element) node;
            newPlaylist.setListTitle(element.getElementsByTagName("Τίτλος_Λίστας").item(0).getTextContent());
            newPlaylist.setDescription(element.getElementsByTagName("Περιγραφή").item(0).getTextContent());
            
            //Στιγμή αποθήκευσης, θεωρούμε την στιγμή εισαγωγής της playlist   
            Timestamp saveTimestamp = new java.sql.Timestamp(now.getTime());
            Date created= saveTimestamp;
            newPlaylist.setCreation(created);
            NodeList list1=element.getElementsByTagName("Song");
            
            //κρατάμε τα τραγούδια που βρίσκονται υπο εισαγωγή playlist
            for (int i = 0; i<list1.getLength(); i++){
                for(int j=0; j<document.getElementsByTagName("Τίτλος_Τραγουδιού").getLength(); j++){
                    Node node1 = list1.item(i);
                        if (node1.getNodeType()== Node.ELEMENT_NODE){                    
                            Element element1 = (Element) node1;                    
                            int eeleee = Integer.parseInt(element.getElementsByTagName("Διάρκεια").item(j).getTextContent());                    
                            try {  
                                //αναζήτηση τραγουδιού στη βάση. Μπρεί να είναι τραγούδι σε άλμπουμ καλλιτέχνη ή συγκροτήματος
                                try {    
                                    Query q1=RadioStation_appPUEntityManager.createQuery("SELECT s FROM Song s WHERE s.songTitle=\""+element.getElementsByTagName("Τίτλος_Τραγουδιού").item(j).getTextContent()+"\" AND s.albumId.artistId.artisticName=\""+element.getElementsByTagName("Καλλιτέχνης_Συγκρότημα").item(j).getTextContent()+"\" AND s.duration="+eeleee, Song.class);
                                    addSong=(Song) q1.getResultList().get(0); 
                                    songs.add(addSong);
                                } catch (ArrayIndexOutOfBoundsException ae) {
                                    Query q1=RadioStation_appPUEntityManager.createQuery("SELECT s FROM Song s WHERE s.songTitle=\""+element.getElementsByTagName("Τίτλος_Τραγουδιού").item(j).getTextContent()+"\" AND s.albumId.groupId.groupName=\""+element.getElementsByTagName("Καλλιτέχνης_Συγκρότημα").item(j).getTextContent()+"\" AND s.duration="+eeleee, Song.class);
                                    addSong=(Song) q1.getResultList().get(0); 
                                    songs.add(addSong);
                                }
                            } catch (ArrayIndexOutOfBoundsException ai) {
                            JOptionPane.showMessageDialog(this , "Αφαίρεση τραγουδιών που δεν υπάρχουν πια στην βάση", "Μήνυμα", JOptionPane.ERROR_MESSAGE);
                            }
        
                        }       
                }
            }
         } catch (Exception ex) {
                System.out.println("Δεν επιλέχθηκε κάποιο αρχείο ή cancel"); //δεν εμφανίζουμε σε JOptionPane γιατί δεν θέλουμε να σταματάμε την ροή χειρισμού του. Υπάρχει εδώ βοηθητικά
                return;
            }  
          
        
        //κρατάμε όλα τα τραγούδια
        Query q2=RadioStation_appPUEntityManager.createQuery("SELECT s FROM Song s", Song.class);
        List<Song> allSongs=new ArrayList();
        allSongs= q2.getResultList();
        
        //αποθηκεύουμε τη νέα playlist στη βάση
            try {
                RadioStation_appPUEntityManager.getTransaction().begin();
                RadioStation_appPUEntityManager.persist(newPlaylist);
                RadioStation_appPUEntityManager.getTransaction().commit();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this , "Υπάρχη ήδη λίστα με αυτό το όνομα", "Μήνυμα", JOptionPane.ERROR_MESSAGE);
                return;
            }
    
        //προσθέτουμε τα τραγούδια στην λίστα (και αντίστροφα καθώς έχουμε σχέση n-m)
        Query q3=RadioStation_appPUEntityManager.createQuery("SELECT pl FROM Playlist pl WHERE pl.listId=(SELECT MAX(p.listId) FROM Playlist p)", Playlist.class);
        Playlist lastList=(Playlist) q3.getResultList().get(0); //παίρνουμε την playlist που μόλις αποθηκεύσαμε
        Playlist setSongList=RadioStation_appPUEntityManager.find(Playlist.class, lastList.getListId());
        RadioStation_appPUEntityManager.getTransaction().begin();
            for(Song s: allSongs) {
                boolean flag=false;
            for (Song plSong : songs) {
                if(Objects.equals(s.getSongId(), plSong.getSongId())) flag=true;
            }
                if(flag) {
                    Song sng =RadioStation_appPUEntityManager.find(Song.class, s.getSongId());
                    sng.getPlaylistCollection().add(setSongList);
                }
            }
        setSongList.setSongCollection(songs);
        RadioStation_appPUEntityManager.flush();
        RadioStation_appPUEntityManager.clear();
        RadioStation_appPUEntityManager.getTransaction().commit();
        
        playlistList.add(newPlaylist); //"εισάγει" τη νέα playlist στον πίνακα
        jTablePlaylist.repaint();
    }//GEN-LAST:event_jButtonImportXmlActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        mmg.setEnabled(true);
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PlaylistSongGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PlaylistSongGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PlaylistSongGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PlaylistSongGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new PlaylistSongGUI().setVisible(true);
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager RadioStation_appPUEntityManager;
    private javax.swing.JButton jButtonAdd;
    private javax.swing.JButton jButtonDelete;
    private javax.swing.JButton jButtonEdit;
    private javax.swing.JButton jButtonExit;
    private javax.swing.JButton jButtonExportXml;
    private javax.swing.JButton jButtonImportXml;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTablePlaylist;
    private java.util.List<model.Playlist> playlistList;
    private javax.persistence.Query playlistQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
